package com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.configuration;

import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.component.AuthorizationAccessTokenConverter;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.component.CustomTokenEnhancer;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.comstants.SecurityConstants;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.service.AuthUserDetailsService;
import java.util.Arrays;
import javax.sql.DataSource;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 认证服务器配置
 *
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/01/26 11:32
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  /**
   * 自定义UserDetailsService
   */
  private final AuthUserDetailsService authUserDetailsService;
  /**
   * 认证管理器
   */
  private final AuthenticationManager authenticationManager;
  /**
   * Redis连接工厂
   */
  private final RedisConnectionFactory redisConnectionFactory;

  private AuthorizationAccessTokenConverter authorizationAccessTokenConverter;

  private DataSource dataSource;

  private CustomTokenEnhancer customTokenEnhancer;

  /**
   * 用来配置客户端详情服务（ClientDetailsService）， 客户端详情信息在这里进行初始化， 你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
   */
  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource);
  }

  /**
   * 用来配置令牌端点(Token Endpoint)的安全约束.
   */
  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer
        .tokenKeyAccess("permitAll()")
        .checkTokenAccess("permitAll()")
        .allowFormAuthenticationForClients();
  }

  /**
   * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)。
   */
  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    // 将增强的token设置到增强链中
    TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
    enhancerChain
        .setTokenEnhancers(Arrays.asList(customTokenEnhancer, authorizationAccessTokenConverter));
    endpoints
        .authenticationManager(authenticationManager)
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
        .userDetailsService(authUserDetailsService)
        .reuseRefreshTokens(false)
        .tokenStore(tokenStore())
        .tokenEnhancer(enhancerChain);
  }

  @Bean
  public TokenStore tokenStore() {
    RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
    tokenStore.setPrefix(SecurityConstants.FTF_PREFIX + SecurityConstants.OAUTH_PREFIX);
    return tokenStore;
  }

}
